package com.qqt.csr.im.service;

import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.qqt.csr.im.entity.ServiceNode;
import com.qqt.csr.im.enums.OnlineEnum;
import com.qqt.csr.im.mapper.ServiceNodeMapper;
import com.qqt.csr.im.utils.ServiceHelper;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;

import java.util.Date;
import java.util.Objects;

/**
 * @Author: yang hao
 * @Date: 2024/10/14 9:51
 * @Description: 人工客服 服务信息 业务层
 **/
@Slf4j
@Service
public class ServiceNodeService extends ServiceImpl<ServiceNodeMapper, ServiceNode> {

    /**
     * 上线
     * @param ip {@link String} ip地址
     * @param port {@link String} 端口
     */
    public void online(String ip, String port) {
        ServiceNode serviceNode = this.lambdaQuery().select()
                .eq(ServiceNode::getIp, ip)
                .eq(ServiceNode::getPort, port).one();
        if (Objects.nonNull(serviceNode)) {
            serviceNode.setState(OnlineEnum.ONLINE.getCode());
            this.lambdaUpdate().set(ServiceNode::getState, OnlineEnum.ONLINE.getCode())
                    .set(ServiceNode::getUpdateTime, new Date())
                    .eq(ServiceNode::getId, serviceNode.getId()).update();
        } else {
            serviceNode = ServiceNode.builder().ip(ip).port(Integer.parseInt(port))
                    .state(OnlineEnum.ONLINE.getCode()).build();
            save(serviceNode);
        }
        ServiceHelper.INSTANCE.setServiceNode(serviceNode);
    }

    /**
     * 离线
     */
    public void offline() {
        ServiceNode serviceNode = ServiceHelper.INSTANCE.getServiceNode();
        this.lambdaUpdate().set(ServiceNode::getState, OnlineEnum.DOWNLINE.getCode())
                .set(ServiceNode::getUpdateTime, new Date())
                .eq(ServiceNode::getId, serviceNode.getId()).update();
    }

}
